package com.lmt.util;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
import java.util.UUID;

/**
 * AES工具类 from:http://mingzijian.iteye.com/blog/2356445
 * 加解密密码的工具类
 * Date 2018/07/17
 *
 * @author MT-Lin
 */
@SuppressWarnings("ALL")
public class AesPasswordUtil {

    private static String key = "a1ae28c6af384d7f8faefebf8856117e";
    private static int offset = 16;
    private static String transformation = "AES/CBC/PKCS5Padding";
    private static String algorithm = "AES";

    /**
     * 加密
     * @param content 需要加密的内容
     * @return 加密后的数据
     */
    public static String encrypt(String content) throws Exception {
        return encrypt(content, key);
    }

    /**
     * 解密
     * @param content 需要解密的内容
     * @return 解密后的数据
     */
    public static String decrypt(String content) throws Exception {
        return decrypt(content, key);
    }

    /**
     * 加密
     *
     * @param content 需要加密的内容
     * @param key 加密密钥
     * @return 加密后的信息
     * @throws Exception 异常
     */
    public static String encrypt(String content, String key) throws Exception {
        try {
            SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(), algorithm);
            IvParameterSpec iv = new IvParameterSpec(key.getBytes(), 0, offset);
            Cipher cipher = Cipher.getInstance(transformation);
            String charset = SystemConstant.CHARSET_UTF8;
            byte[] byteContent = content.getBytes(charset);
            cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, iv);
            byte[] result = cipher.doFinal(byteContent);
            return Base64.getEncoder().encodeToString(result);
        } catch (Exception e) {
            throw new Exception(e);
        }
    }

    /**
     * AES（256）解密
     *
     * @param content 待解密内容
     * @param key 解密密钥
     * @return 解密之后
     * @throws Exception 异常
     */
    public static String decrypt(String content, String key) throws Exception {
        SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(), algorithm);
        IvParameterSpec iv = new IvParameterSpec(key.getBytes(), 0, offset);
        Cipher cipher = Cipher.getInstance(transformation);
        cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, iv);
        byte[] result = cipher.doFinal(Base64.getDecoder().decode(content));
        return new String(result);
    }

    public static void main(String[] args) throws Exception {
        String s = "hello world";
        // 加密
        System.out.println("加密前：" + s);
        String encryptResultStr = encrypt(s);
        System.out.println(UUID.randomUUID().toString().replace("-",""));
        System.out.println("加密后：" + encryptResultStr);
        // 解密
        System.out.println("解密后：" + decrypt(encryptResultStr));
    }
}
